#!/usr/bin/env python
# -*- coding: utf-8 -*-
import cexapi

import datetime
import time
import re
import sys
import tablePrint
import logging

import os
import platform
import myCEXFunctions


myCexFunc = myCEXFunctions.function()

doLogging=True
logging.basicConfig(format='%(asctime)s; %(message)s', filename='sellatlimit.log',level=logging.DEBUG)

out = sys.stdout
formattab = tablePrint.tableprint()
 
credentialFile = open('credentials.txt', 'r+')

for line in credentialFile:
        resultLine = re.split(';', line)  
        if resultLine[0]=='hannesh':
            apiUser=resultLine[0]
            apiCred1=resultLine[1]
            apiCred2=resultLine[2]      

notOpen=True
while notOpen:
    try:
        demo = cexapi.api(apiUser, apiCred1, apiCred2)
        notOpen=False
    except:
        print "no connection yet"
        time.sleep(60)
        

def getFromBal(GHSBTC,avl_orders):
    retVal=0
    try:
        retVal=float(bal[GHSBTC][avl_orders])
    except:
        retVal=0
    return retVal

def sellAll(ghsAmt,orderbook):
    ghs2sell=ghsAmt
    buyIndex=0
    priceIdx=0
    ghsAmt=1
    achievedAmt=0
    while ghs2sell>0:
        minGHS=min(ghs2sell,orderbook['bids'][buyIndex][ghsAmt])
        price=orderbook['bids'][buyIndex][priceIdx]
        achievedAmt += price*minGHS    
        ghs2sell -= minGHS
        print "demo.place_order('sell',",minGHS,price,")"
        demo.place_order('sell',minGHS,price)
        buyIndex +=1
    return achievedAmt

def buyAll(btcAmt,orderbook):
    btc2buy=btcAmt
    buyIndex=0
    
    priceIdx=0
    ghsAmtIdx=1
    
    usedAmt=0
    boughtGHS=0
    while btc2buy>0:
        price=orderbook['asks'][buyIndex][priceIdx]        
        minBTC=min(btc2buy,price*orderbook['asks'][buyIndex][ghsAmtIdx])
        minGHS=minBTC/price
        #print "price=",price, "minBTC=",minBTC, "minGHS=",minGHS
        usedAmt += minBTC    
        btc2buy -= minBTC
        boughtGHS += minGHS
        print "demo.place_order('buy',",minGHS,price,")"
        demo.place_order('sell',minGHS,price)
        buyIndex +=1
    print "boughtGHS=",boughtGHS, "usedBTC=",usedAmt
    return usedAmt



notOpen=True
while notOpen:
    try:
        bal = demo.balance()
        notOpen=False
    except:
        print "connection not open yet"
        time.sleep(60)
        
ghs_avl=getFromBal('GHS','available')
ghs_orders=getFromBal('GHS','orders')
ghs_tot = ghs_avl+ghs_orders


criticalAmt=0.851
sell_all_allowed=False
highMode=False
run=True

while run:
    try:        
        if ghs_avl<0.1:
            print "ghs_avl<0.1" 
            print "Profile asks (relevant wenn ich kaufen will)"           
            virtBuy=myCexFunc.showRateProfile(77.19, 11,2,'asks',logging,demo,showTable = True)
            print "Profile bids (also wenn ich verkaufen will)"
            virtSell=myCexFunc.showRateProfile(77.19, 11,2,'bids',logging,demo,showTable = True)
            criticalRate=0.0066
            if virtBuy['rate']['1']<criticalRate:
                print "good rate@",virtBuy['rate']['1']                
                btcAmt=getFromBal('BTC','available')
                orderbook=demo.order_book()
                print "BTCAmt=",btcAmt
                #buyAll(btcAmt,orderbook)
                #run=False
            else:
                print "not good enough rate@",round(virtBuy['rate']['1'],6)
                print "should be under",criticalRate                
                
        else:
            print "Virtual Sell, ghs=",ghs_avl
            virtProfit=myCexFunc.showRateProfile(ghs_avl, 11,2,'bids',logging, demo, showTable = True)
            #print "Virtual Buy, ghs=",ghs_avl
            virtBuy=myCexFunc.showRateProfile(ghs_avl, 11,2,'asks', logging, demo, showTable = False)
        
            btc_avl=myCexFunc.getFromBal('BTC','available')
            print "btc_avl=",btc_avl
        
            achievedRate=virtProfit['achievedRate']
            if highMode:
                allProfit=virtProfit['achievedAmt']+btc_avl
                
            else:
                allProfit=virtProfit['achievedAmt']
        
            if allProfit>criticalAmt:
                print "Critical; allProfit=",allProfit,">",criticalAmt, "=criticalAmt; sell all"  
                          
                if sell_all_allowed:
                    print "sell all"
                    orderbook=demo.order_book()
                    sellAll(ghs_avl,orderbook)
                    run=False
                else:
                    print "sell all not allowed"            
            else:                              
                print "not critical; allProfit=@"+str(round(allProfit,5)), "critical@"+str(criticalAmt)
                #print "achievblRate(4selling)=",round(achievedRate,7)
                #print virtBuy
                print "               buyAllAmt@"+str(round(virtBuy['achievedAmt'],5))
                logging.info("not critical; allProfit=@"+str(round(allProfit,5))+" critical@"+str(criticalAmt))
                if not sell_all_allowed:
                    print "(but sell all currently not allowed anyway)"
                else:
                    print "sell all allowed"    
        time.sleep(60)
    except:
        print "General Exception"
        raise 
        time.sleep(60)

